<?php
namespace Modules\Book\Library;

use Core\Mvc\Model\Struct;
use Modules\Book\Models\NodeBook;
use Core\Forms\Form;
use Phalcon\Di;

class Common
{
    public static function bookItemSave(Form $form)
    {
        $data = $form->getData();
        $options = $form->getUserOptions();
        $nodeBook = NodeBook::findFirst([
            'conditions' => [
                'bid' => $options['book_id'],
            ],
        ]);
        if(!$nodeBook){
            return false;
        }
        $struct = new Struct($nodeBook->toc);
        $id = $data['id'];
        unset($data['id']);
        if ($form->isEdit()) {
            $struct->edit($id, $data);
        } else {
            $struct->add($id, $data);
        }
        $nodeBook->toc = $struct->getData();
        if ($nodeBook->save()) {
            return $nodeBook;
        }

        return false;
    }

    public static function bookSort($hierarchy,$data)
    {
        $di = Di::getDefault();
        $output = [];
        foreach ($hierarchy as $key => $value) {
            $itemInfo = explode(',', $key);
            if (count($itemInfo) != 2) {
                $di->getShared('flash')->error('ID信息错误');
                return false;
            }
            $output[$itemInfo[0]] = [
                'title' => $itemInfo[1],
            ];
            if (is_array($value)) {
                $output[$itemInfo[0]]['son'] = self::bookSort($value);
            }
        }
        return $output;
    }

    //术语排序
    public static function saveBookItemSort($hierarchy)
    {
        $widget = 1;
        $start = 1;
        //Config::printCode($hierarchy);
        foreach ($hierarchy as $key => $value) {
            $nodeBook = NodeBook::findById($key);
            if ($start == 1) {
                $widget = $nodeBook->widget;
                if ($nodeBook->pid != 0) {
                    $nodeBook->pid = 0;
                }
                $start++;
                $state = $nodeBook->save();
            } else {
                $nodeBook->pid = 0;
                $nodeBook->widget = $widget;
                $state = $nodeBook->save();
            }
            $widget++;
            if (!empty($value)) {
                $widget = self::_saveNodeBookSort($value, $widget, $nodeBook->id);
            }
        }
        return true;
    }

    protected static function _saveNodeBookSort($hierarchy, $widget, $pid)
    {
        foreach ($hierarchy as $key => $value) {
            $nodeBook = NodeBook::findFirst($key);
            $nodeBook->widget = $widget;
            $nodeBook->pid = $pid;
            $nodeBook->save();

            $widget++;
            $pid = $nodeBook->id;
            if (!empty($value)) {
                self::_saveNodeBookSort($value, $widget, $pid);
            }
        }
        return $widget;
    }
    //术语排序结束
}